/**
 * Created by hejiahui on 2018/6/23.
 */
import  jwt from 'jsonwebtoken'
import { jwtSercert, expiresIn } from '../../config/index'
import Page from '../common/pageController'

const md5 = require('md5');
const ObjectId = require('mongoose').Types.ObjectId
const userModel  = require('../../mongodb/model/user.js')
const taskModel = require('../../mongodb/model/task.js')
const ignoreData = { _id: 0 ,__v: 0, userId : 0 }

const page = new Page()

const createToken = function(userInfo ) {
    const user = {
        userId : userInfo._id ,
        name : userInfo.name
    }
    return jwt.sign({
        ...user
    },  jwtSercert, { expiresIn })
}

const getUserInfoFromToken = function (ctx){
    return ctx.state.user
}

const commonResult = function(code, msg, data ){
    return {
        code : code || 0 ,
        msg  ,
        data ,
        serverTime : +new Date()
    }
}

const commonPageResult = function(code, msg, result  ){
    const { data, pageNum ,pageSize ,lastValue ,hasMore } = result
    return {
        code : code || 0 ,
        msg  ,
        data, pageNum ,pageSize ,lastValue ,hasMore ,
        serverTime : +new Date()
    }
}

// task
// 任务相关
const task = {
    // 新建任务
    createTask: async (ctx, next) => {
        const body = ctx.request.body
        const { userId } = ctx.state.user
        const dateTamp = new Date( body.arrivalTime )
        const arriveDate = task._formatDate(dateTamp)
        const data = Object.assign({}, body, {userId, arriveDate})
        let res = await taskModel.create(data)
        const taskId = res._id
        try{
            if(res){
                ctx.send( commonResult(0, 'success', {
                    taskId
                }))
            }
        } catch (err){
            throw err
        }
    },
    _formatDate( dateTamp ){ // 必须为Date
        const Year = dateTamp.getFullYear()
        const Month = dateTamp.getMonth() + 1
        const Day = dateTamp.getDate()
        const arriveDate =   `${Year}-${Month}-${Day}`
        return arriveDate
    },
    updateTask : async (ctx, next) =>{
        const  taskId  = ctx.params.taskId
        const body = ctx.request.body
        const { userId }= ctx.state.user
        const data = body
        let res = await taskModel.update({
            _id : ObjectId( taskId )
        }, data)
        try{
            if(res){
                ctx.send( commonResult(0, 'success', {
                    taskId
                }))
            }
        } catch (err){
            throw err
        }
    },
    // 删除任务
    deleteTask: async (ctx, next) => {
        const taskId = ctx.params.taskId
        const { userId } = ctx.state.user
        try{
            let res = await taskModel.remove({
                '_id' : ObjectId(taskId),
                userId ,
            }, { _id: 0 ,__v: 0 })
            if(res){
                ctx.send( commonResult(500, 'success') )
            }
            else{
                ctx.send( commonResult(0, '没有权限') )
            }
        } catch(err){
            throw  err ;
        }
    },
    // 获取任务列表
    getTaskList: async (ctx, next) => {
         // 按分类来查
         let  condition = {}
         const type = ctx.query.taskType
         const date = ctx.query.date
         const pageSize = ctx.query.pageSize
         const pageNum = ctx.query.pageNum
         const _lastValue =  ctx.query.lastValue
         const lastValue = _lastValue && _lastValue !== '0' ? ctx.query.lastValue : null
         try{
             condition = task._setTastcondition(ctx, type, date)
             let res = await page.pageQuery( taskModel, pageNum ,pageSize , lastValue , condition )
             let result = page.PageResult(pageNum, pageSize,res)
             ctx.send( commonPageResult(0, 'success', result ) )
         } catch(err){
            throw  err ;
         }
    },
    _setTastcondition(ctx , type ,date = ''){
      const { userId } = ctx.state.user
      const nowDate = task._formatDate( new Date() )
      let todayInitDate = new Date()
          todayInitDate.setHours(0)
          todayInitDate.setMinutes(0)
          todayInitDate.setMilliseconds(0)
          todayInitDate.setSeconds(0)

      let onedayTamp = 24 * 60 * 60 * 1000
      let threeDayBefore = +todayInitDate - onedayTamp
      let condition = { userId }
      if(  date ){
          condition.arriveDate = date
      }
      switch(type){
          case 'nearest' : condition.arrivalTime = {
              $gt : threeDayBefore,
              $lte : +todayInitDate
          };break ;
          case 'complete' : condition.arrivalTime = {
              $lte : +Date.now()
          };break ;
          case 'today': condition.arriveDate = {
              $eq : nowDate
          }; break ;
      }
      return condition
    },
    // 查看、更新
    taskDetail:  async (ctx, next) => {
        const taskId = ctx.params.taskId
        const { userId } = ctx.state.user
        try{
            let res = await taskModel.findOne({
                '_id' : taskId
            }, ignoreData)
            if(!res){
                ctx.send( commonResult(500, '查找的任务不存在', res) )
            }
            else{
                ctx.send( commonResult(0, 'success', res) )
            }

        } catch(err){
            throw  err ;
        }
    },
    // 根据文字搜索任务 (模糊检索)
    searchTaskFromText : async (ctx, next) => {
        const { content, taskType } = ctx.query
        let condition = task._setTastcondition(ctx, taskType )
        // 模糊搜索 多条件时 $or :[{ condition1 },{condition2}]
        condition.title =  { $regex  : content ,$options: '$i' }
        try{
            let res = await taskModel.find(condition)
            ctx.send( commonResult(0, 'success', res) )
        }catch (err) {
            throw err;
        }
    }
}

module.exports = {
    ...task
    // 新建任务

}

